import { FC,useState,useEffect } from 'react';
import { Form,Button,Checkbox,TreeSelect,message } from 'antd';
import type { CheckboxOptionType, GetProp } from 'antd';
import { getUserList,grantDirectoryUserShare } from '../../../apis/backhub/directory';

interface PermissionFormProps {
  directory: number; // 文件目录
  directoryName:string;
}
interface BaseTree {
  title: string;
  value:string;
  children?:BaseTree[]
}
const PermissionForm: FC<PermissionFormProps> = ({ directory,directoryName}) => {
	const [value, setValue] = useState<string[]>();
	const [checkedValues,setCheckedValues] = useState<string[]>();
	const [treeData, setTreeData] = useState<BaseTree[]>();
	useEffect(() => {
	  fetchData();
	}, []);
	const fetchData = async() => {
		const treeRes = await getUserList()
		if(treeRes.status){
			const tempData:BaseTree[] = []
			treeRes.data.map(item=>{
				tempData.push({
					value: `${item.id}`,
					title: `${item.name}`,
					children: []
				});
			})
			setTreeData(tempData)
		}
	};
	const onTreeChange = (newValue: string[]) => {
		setValue(newValue);
	};
	const [form] = Form.useForm();
	const onChange: GetProp<typeof Checkbox.Group, 'onChange'> = (checkedValues) => {
	  setCheckedValues(checkedValues as string[])
	};
	const options: CheckboxOptionType<string>[] = [
	  { label: '新建', value: '6' },
	  { label: '编辑', value: '7'},
	  { label: '查看', value: '8'},
	  { label: '下载', value: '9'},
	  { label: '删除', value: '10'}
	];
	const handleSave=async()=>{
		const res = await grantDirectoryUserShare({directoryId:directory,userIds:value?.join(','),permissionIds:checkedValues?.join(',')});
		if(res.status&&res.data.success){
			form.setFieldsValue({
			    value: [],
				checkedValues:[]
			})
			setValue([]);
			setCheckedValues([]);
			message.success('新增成功');
		}else{
			message.error(res.data.message)
		}
	}
	
	return (
		<div className="upload-container">
			<Form
				form={form}
				layout="vertical"
				onFinish={handleSave}
			>
			  <Form.Item
				label="目录名称"
				name="name"
			  >
				<text>{directoryName}</text>
			  </Form.Item>
			  <Form.Item
					label="选择人员"
					name="value"
					rules={[{ required: true, message: '请选择人员' }]}
				>
					<TreeSelect
					  showSearch
					  style={{ width: '100%' }}
					  value={value}
					  /*styles={{
						popup: { root: { maxHeight: 400, overflow: 'auto' } },
					  }}*/
					  placeholder="请选择"
					  allowClear
					  multiple
					  treeDefaultExpandAll
					  onChange={onTreeChange}
					  treeData={treeData}
					/>
			  </Form.Item>
			  <Form.Item
				  label="文件权限"
				  name="checkedValues"
				>
					<Checkbox.Group options={options} value={checkedValues} onChange={onChange} />
				</Form.Item>
			  <Form.Item>
				<Button type="primary" htmlType="submit">
				  保存
				</Button>
			  </Form.Item>
			</Form>
		</div>
	);
};

export default PermissionForm;
